import React from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch } from '@/store/hook';
import { fetchLogin } from '@/store/modules/user';

const Login = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();

  const onFinish = async (values) => {
    try {
      const result = await dispatch(fetchLogin(values)).unwrap();
      message.success('登录成功');
      navigate('/');
    } catch (error) {
      message.error('登录失败: ' + error.message);
    }
  };

  const handleRegister = () => {
    // 模拟注册逻辑
    const adminUser = {
      username: 'admin',
      password: 'admin123',
      name: '系统管理员',
      role: '管理员'
    };
    
    // 这里应该是一个真实的API调用
    // const response = await api.post('/register', adminUser);
    // 模拟成功响应
    const response = { 
      data: { 
        token: 'fake-admin-token',
        userInfo: {
          id: 1,
          username: 'admin',
          name: '系统管理员'
        },
        permissions: [
          'user:list', 'user:create', 'user:edit', 'user:delete',
          'role:list', 'role:create', 'role:edit', 'role:delete'
        ],
        roles: ['admin']
      } 
    };

    // 设置用户信息
    localStorage.setItem('token', response.data.token);
    localStorage.setItem('userInfo', JSON.stringify(response.data.userInfo));
    localStorage.setItem('permissions', JSON.stringify(response.data.permissions));
    localStorage.setItem('roles', JSON.stringify(response.data.roles));

    message.success('管理员账户创建成功！');
    navigate('/');
  };

  return (
    <div style={{ maxWidth: 300, margin: '100px auto' }}>
      <h2 style={{ textAlign: 'center' }}>系统登录</h2>
      <Form
        form={form}
        name="login"
        onFinish={onFinish}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名!' }]}
        >
          <Input placeholder="用户名" />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password placeholder="密码" />
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked">
          <Checkbox>记住我</Checkbox>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form.Item>
      </Form>

      <div style={{ textAlign: 'center', marginTop: 16 }}>
        <Button type="link" onClick={handleRegister}>
          首次使用？创建管理员账户
        </Button>
      </div>
    </div>
  );
};

export default Login;
